package drds.binlog.database_driver;

import drds.binlog.common.Authors;
import drds.binlog.database_driver.packets.client.QueryCommandPacket;
import drds.binlog.database_driver.packets.server.ErrorPacket;
import drds.binlog.database_driver.packets.server.OkPacket;
import drds.binlog.database_driver.utils.Packets;
import drds.common.Author;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 默认输出的数据编码为UTF-8，如有需要请正确转码
 */
@Slf4j
@Author(name = Authors.LI_YANG)
public class UpdateExecutor
{


    private Connector connector;

    public UpdateExecutor(Connector connector) throws IOException
    {
        if (!connector.isConnected())
        {
            throw new IOException("should execute connector.connect() first");
        }

        this.connector = connector;
    }

    /*
     * public UpdateExecutor(SocketChannel ch){ this.channel = ch; }
     */

    public OkPacket update(String updateString) throws IOException
    {
        QueryCommandPacket queryCommandPacket = new QueryCommandPacket();
        queryCommandPacket.setQueryString(updateString);
        byte[] bodyBytes = queryCommandPacket.toBytes();
        Packets.writeBody(connector.getSocketChannel(), bodyBytes);

        log.debug("read update result...");
        byte[] body = Packets.readBytes(connector.getSocketChannel(),
                Packets.readHeader(connector.getSocketChannel(), 4).getPacketBodyLength());
        if (body[0] < 0)
        {
            ErrorPacket errorPacket = new ErrorPacket();
            errorPacket.fromBytes(body);
            throw new IOException(errorPacket + "\n with command: " + updateString);
        }

        OkPacket okPacket = new OkPacket();
        okPacket.fromBytes(body);
        return okPacket;
    }
}
